package com.luhuiguo.cms.server.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.entity.Channel;
import com.luhuiguo.cms.server.service.ChannelService;
import com.luhuiguo.cms.server.service.MapperService;
import com.luhuiguo.cms.shared.model.ChannelModel;
import com.luhuiguo.cms.shared.rpc.UpdateChannel;
import com.luhuiguo.cms.shared.rpc.UpdateChannelResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;
import com.luhuiguo.gwt.validation.server.ServerValidation;

@Component
public class UpdateChannelHandler implements ActionHandler<UpdateChannel, UpdateChannelResult> {

    @Autowired
    private MapperService mapperService;

    @Autowired
    private ChannelService channelService;

    @Override
    @PreAuthorize("isAuthenticated()")
    public UpdateChannelResult execute(UpdateChannel action, ExecutionContext context) throws ActionException {
        Channel c = mapperService.map(action.get(), Channel.class);
        new ServerValidation(false).length(c.getName(), 1, 20, "name").length(c.getTitle(), 1, 100, "title").validate();

        channelService.updateChannel(c);
        return new UpdateChannelResult(action.get(), mapperService.map(c, ChannelModel.class));
    }

    @Override
    public Class<UpdateChannel> getActionType() {
        return UpdateChannel.class;
    }

    @Override
    public void rollback(UpdateChannel action, UpdateChannelResult result, ExecutionContext context)
            throws ActionException {

    }

}
